<?php
	class CommonGenerator
	{
		/**
		 * generateUniqueId
		 */
		public static function generateUniqueId($i = null)
		{ /*{{{*/
			return (isset($i) && $i > 0) ? str_replace('.', '_', microtime(true)) . '_' . getmypid() . '_' . $i
				: str_replace('.', '_', microtime(true)) . '_' . getmypid();
		} /*}}}*/

		/**
		 * generateCurrentIso8601Dates
		 */
		public static function generateCurrentIso8601Dates()
		{ /*{{{*/
			$date = new Zend_Date();

			# convert current date to individual chars in iso 8601 format
			$date_8601 = $date->get(Zend_Date::ISO_8601);
			$date_chars = str_split($date_8601);

			# go thru each number and subtract it from 9 for inversion
			foreach ($date_chars as $char)
			{
				if (is_numeric($char))
					$inverted_8601 = (isset($inverted_8601)) ? $inverted_8601 . (9 - $char) : (9 - $char);
				else
					$inverted_8601 = (isset($inverted_8601)) ? $inverted_8601 . $char : $char;
			}
			
			# return a hash containing the normal iso 8601 date and its inversion
			return array('normal' => $date_8601, 'inverted' => $inverted_8601);
		} /*}}}*/

		/** 
		 * generateFilenameFromContentType
		 * @throws CommonGeneratorException
		 */
		public static function generateFilenameFromContentType($item, $content_type)
		{ /*{{{*/
			switch ($content_type)
			{
				case 'image/jpeg':
					$filename = $item . '.jpeg';
					break;
				case 'image/gif':
					$filename = $item . '.gif';
					break;
				case 'image/x-png':
					$filename = $item . '.png';
					break;
				case 'video/3gpp2':
					$filename = $item . '.3g2';
					break;
				default:
					// unexpected content-type! this should never be hit, but throw an exception anyway.
					$ex_msg = 'Unexpected MIME Content-Type encountered.'
						. " Content-Type was '" .  $content_type . "'.";
					throw new CommonGeneratorException($ex_msg, 0);
			}
			
			return $filename;
		} /*}}}*/

		/** 
		 * getUniqueUrlString
		 * @throws Amazon_SimpleDB_Exception
		 */
		public static function generateUniqueMediaUrlString($str)
		{ /*{{{*/
			$media_sdb_mgr = new MediaSDBManager();
			$exists = true;
			$count = 2;
	
			# attempt to create a unique url acceptable string
			$new_url = $orig_url = preg_replace("/[^a-zA-Z0-9_]+/", "_", 
				str_replace(' ', '_', $str)); 
			
			# check media db and change end of string count until url is unique
			while($exists)
			{
				# query the database for the url we're attempting to use
				$query = "['url' = '$new_url']";
				$media = $media_sdb_mgr->query($query);

				if (sizeof($media) > 0) 
				{ 
					$new_url = $orig_url . '_' . $count;
					$count++;
				}
				# url doesn't exist yet. use it
				else
				{
					$exists = false;
				}
			}
			
			return $new_url;
		}/*}}}*/
	}
